--
-- @Author:      qinxugao
-- @DateTime:    2018-03-30 23:05:48
-- @Description: 消息的处理

local skynet = require "skynet"
local config = require "configquery"
local json = require "cjson"
local sharedata = require "sharedata"
local NodeMessage = require "NodeMessage"
local log = require "Log"
require "common"

local Command = class("Command")

---------------------------------------------------------
-- Private
---------------------------------------------------------
function Command:ctor(message)
	self.msg = message
	self.tableList = {} --所有桌子列表
	self.tbField = {} --场次
	self.nodeMessage = NodeMessage.new()

	self.tbGamePrivateid = {} --私人桌id
	self.tbMaxGamePrivateid = {}
	self.tbMinGamePrivateid = {}
	self.tbUserTable = {} --玩家创建的私人桌子
	self.prRoomid = 99 --私人桌场次id
	self.maxTableNum = 10 --能创建的私人桌最大数
	self:register()
	self:loadTableConfig()	
end

--注册本服务里的消息
function Command:register()

	self.msg:registerSelf('player_num_req',handler(self,self.getGamePlayerNum))
	self.msg:registerSelf('changetable_req',handler(self,self.changeTable))
	self.msg:registerSelf('enter_table_req',handler(self,self.enterTable))
	self.msg:registerSelf('set',handler(self,self.setTablePlayerNum))
	self.msg:registerSelf('get',handler(self,self.getTablePlayerNum))
	self.msg:registerSelf('get_all',handler(self,self.getAllPlayerNum))		
	self.msg:registerSelf('create_private',handler(self,self.createPrivate))		
	self.msg:registerSelf('close_private',handler(self,self.closePrivate))


end
	
--加载房间配置
function Command:loadTableConfig()
	
	local loadTable = function (tbConfig)
		-- print("____tbConfig__",tbConfig)
		for k,v in pairs(tbConfig) do 
			self.tbField[k] = v
		end		
	end

	local function callback()
		for k,v in pairs(g_gameType) do 	
			loadTable(config[v.cfgRoom])
		end		
	end
	--房间配置更新
	skynet.fork(function()
		while(true) do 
			callback()
			skynet.sleep(1000)
		end
	end)

	
end

--常规入桌
function Command:getNormalTable(roomType,chip)
	print("--------------------->getNormalTable", roomType,chip)
	local tb  = {}		
	local res = '正常'
	local room = self.tbField[roomType] --场次配置
	if not room then 
		res = '场次不存在'
		return tb,res
	end
	--进入游戏的规则
	local td = room.sub_id * 1000000 	
	local count = 0
	local runTable
	local tableNum = 1000 --一个场所拥有的桌子数
	local tableid
	for i=1, tableNum do 
		tableid = td + i
		runTable = self.tableList[tableid]
		if not runTable then	
			runTable = {0,room.max_num} --{当前人数，最大人数}
			self.tableList[tableid] = runTable
		end
		if chip < room.min_money then --钱不够入场
			print("_____金币不够入场_______",chip,room.min_money)
			res = -3
			-- res = room.min_money - chip
			return tb,res
		elseif chip > room.max_money then --钱超过最大入场

		end
		count = runTable[1]
		if count < runTable[2] then --把人数已经满的房间除去
			table.insert(tb,{id=tableid,count=count,room=room})				
		end
		if #tb > 10 then 
			--有10个符合条件的桌子可以选就不用继续
			break
		end			
		
	end	
	return tb,res
end

---------------------------------------------------------
-- CMD
---------------------------------------------------------

--设置桌子人数
function Command:setTablePlayerNum(tableid, value)
	local last = self.tableList[tableid]
	if last then
		last[1] = value
	end
end

--取桌子人数
function Command:getTablePlayerNum(tableid)
	local tb = self.tableList[tableid]
	if tb and tb[1] then 
		return tb[1]
	end
	return 0
end

--所有在游戏人数
function Command:getAllPlayerNum()
	local allnum = 0
	for id, v in pairs(self.tableList) do
		allnum = allnum + v[1]
	end
	return allnum
end

--指定的几个桌子的人数
function Command:getTablesPlayerNum( tableids )
	local list = {}
	for k, id in pairs(tableids) do
		local v = self.tableList[id] 
		if v then
			list[id] = v[1]
		end
	end
	return list
end


---------------------------------------------------------
-- REQUEST
---------------------------------------------------------
--取游戏各个场次人数
function Command:getGamePlayerNum(playerid,gameid)
	local tbPlayerNum  = {}		
	--进入游戏的规则
	local name = getGameRoomConfig(gameid) --config.niuniu_config
	local tbRoomCfg = config[name]
	if not tbRoomCfg then
		return tbPlayerNum
	end
	for roomid,v in pairs(tbRoomCfg) do 
		local playerNum = 0
		local tableid = roomid * 1000000
		for i=1 ,v.table_num do --每个场的所有桌子
			playerNum = playerNum + self:getTablePlayerNum(tableid+i)
		end
		tbPlayerNum[roomid] = playerNum
	end
	print("###################",tbPlayerNum)
	return tbPlayerNum
end

--取桌子id
function Command:enterTable( playerid,roomType,tableid,chip)
	local tb = {}
	local tbId = {}
	local res = nil
	--通过房间类型进入
	if not roomType or not chip then 
		log.error("________无场次或金钱___palyerid="..playerid.." chip="..chip.." roomType="..roomType)
		res = '进入场次错误'
		return {-1,res}
	end
	--游戏类型
	local gid = getGameIdbyRoom(roomType)
	local name = getGameName(gid)
	tb,res = self:getNormalTable(roomType,chip)
	-- print("____tb___res__",tb,res)
	if #tb <= 0 then --房间已满		
		log.error("________取不到桌子________",playerid,tb,res)				
		if res==-3 then 
			--金币不足
			return {-3,res}
		end
		-- res = '桌子已满'
		return {-2,res}
	end
	--人数多的优化
	local function sort_table( tb1,tb2 )
		if tb1.count ~= tb2.count then 
			return tb1.count > tb2.count
		end
		return false
	end
	if #tb > 1 then 
		table.sort(tb, sort_table)
	end
	for i=1,3 do 
		if tb[i] and tb[i].count > 0 then 
			table.insert(tbId,tb[i].id)
		end
	end
	local id = tb[1].id
	if #tbId > 1 then 
		id = tbId[math.random(1,#tbId)]
	end
	return {id,res}
end

--改变桌子
function Command:changeTable(playerid,tableid,chip)
	local roomType = getRoomType(tableid)
	--游戏类型
	local gid = getGameIdbyRoom(roomType)
	local name = getGameName(gid)
	local tb = {}
	local res = nil
	tb,res = self:getNormalTable(roomType,chip)
	for k,v in pairs(tb) do 
		if v.id == tableid then 
			table.remove(tb,k)
			break
		end
	end	
	if #tb <= 0 then --房间已满		
		print("______error__取不到桌子________")
		return false
	end	
	--人数多的优先
	local function sort_table( tb1,tb2 )
		if tb1.count ~= tb2.count then 
			return tb1.count > tb2.count
		end
		return false
	end

	if #tb > 1 then 
		table.sort(tb, sort_table)
	end
	return tb[1].id
end



------------------------------私人桌
--创建私人桌 (创建桌子现在是php做， 这个后面基本用不到的了)
function Command:createPrivate(playerid, args)
	local gameid = args.gameid+10
	local setting = args.setting --json 串
	local maxPlayerNum = 3
	local tableid 
	local data
	local res
	if not self.tbGamePrivateid[gameid] then 
		--取6位数码
		local sql = "select * from private_num where server_gameid="
		res = self.nodeMessage:callService("mysql_service", "execute", sql ..gameid)
		-- print("_____________data__22222_______",res)
		if not res or not next(res[1]) then 
			return false
		end
		res = res[1]
		self.tbGamePrivateid[gameid] = res.table_num
		self.tbMaxGamePrivateid[gameid] = res.max_table_num
		self.tbMinGamePrivateid[gameid] = res.min_table_num
	end
	if not self.tbUserTable[playerid] then 
		self.tbUserTable[playerid] = {}
	end
	-- if #self.tbUserTable[playerid] > self.maxTableNum then --个人最大创建的桌子数
	-- 	return false
	-- end
	local function getNum()
		self.tbGamePrivateid[gameid] = self.tbGamePrivateid[gameid] + 1
		if self.tbGamePrivateid[gameid] > self.tbMaxGamePrivateid[gameid] then 
			self.tbGamePrivateid[gameid] = self.tbMinGamePrivateid[gameid]
		end
		local sql = string.format("update private_num set table_num = %d where server_gameid = %d",
			self.tbGamePrivateid[gameid],gameid)
		res = self.nodeMessage:callService("mysql_service", "execute", sql)		
		tableid = tonumber(""..gameid ..self.prRoomid.. self.tbGamePrivateid[gameid])
	end
	getNum()
	local sql = "select * from private_tables where tableid="..tableid
	local res = self.nodeMessage:callService("mysql_service", "execute", sql)	
	res = res[1]
	while next(res) do 
		--桌子已存在
		getNum()		
		res = self.nodeMessage:callService("mysql_service", "execute", sql)
		res = res[1]
	end	

	self.tableList[tableid] = {0,maxPlayerNum}
	table.insert(self.tbUserTable[playerid],tableid)

	-- local tableNum = tonumber(""..math.random(10,99) .. self.tbGamePrivateid[gameid])
	local tableNum = self.tbGamePrivateid[gameid]
	local gid = gameid%10
	--写入数据库
	local data = {
		tableid = tableid,
		setting = setting,
		managerid = playerid,
		number = tableNum,
		gameid = gameid,
		create_time = os.time(),
		playtype=1,
		game=gid,
	}
	-- self.nodeMessage:callService('dbmgr_service','add_private_tables',data,true)
	local sql = string.format("insert into private_tables values(%d,%s,%d,%d,%d,%d,%d)",
		tableid,setting,playerid,tableNum,gameid,os.time(),1,gid)
	local res = self.nodeMessage:callService("mysql_service", "execute", sql)
	return {tableid,tableNum}
end

--关闭私人桌
function Command:closePrivate(playerid, tableid)
	print("________closePrivate______",tableid)
	local data = {
		tableid = tableid,
	}
	local sql = "delete from private_tables where tableid="..tableid
	local res = self.nodeMessage:callService("mysql_service", "execute", sql)		
	-- local res = self.nodeMessage:callService('dbmgr_service','delete_private_tables',data)		
	-- print("________res___",res)
	self.tableList[tableid] = nil
	if self.tbUserTable[playerid] and next(self.tbUserTable[playerid]) then 
		for k,v in pairs(self.tbUserTable[playerid]) do 
			if tableid == v then 
				table.remove(self.tbUserTable[playerid],k)		
				break
			end
		end	
	end
	return true
end

return Command